package com.bobi.tfca.ui.article

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.databinding.FragmentWriteArticleBinding
import com.bobi.tfca.network.response.ArticleResponse
import com.bobi.tfca.ui.adapter.WriteParagraphAdapter
import com.bobi.tfca.util.RealPathUtil
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


class WriteArticleFragment : BaseFragment<FragmentWriteArticleBinding, ArticleFragmentVM>(
    FragmentWriteArticleBinding::inflate,
    ArticleFragmentVM::class.java,
    true
) {
    // 会员RV
    private lateinit var paragraphRV: RecyclerView
    private lateinit var imagePickerLauncher: ActivityResultLauncher<Intent>
    private var imageView: ImageView? = null
    private var position: Int = 0

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private val REQUIRED_PERMISSIONS = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE
    )

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            if (permissions.all { it.value }) {
                // 如果所请求的所有权限都被授予，则执行相应的操作，比如打开相册
            } else {
                // 如果有任何一个权限被拒绝，则可以向用户解释为什么需要这些权限，并提供一个再次请求的机会
                Toast.makeText(requireActivity(), "选择图片需要权限", Toast.LENGTH_SHORT).show()
            }
        }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun checkPermissions(): Boolean {
        val isAllGranted = REQUIRED_PERMISSIONS.all {
            ContextCompat.checkSelfPermission(
                requireContext(),
                it
            ) == PackageManager.PERMISSION_GRANTED
        }
        // 如果权限没有授予，请求权限
        if (!isAllGranted) {
            requestPermissionLauncher.launch(REQUIRED_PERMISSIONS)
            return false
        } else {
            // 如果权限已被授予，则执行相应的操作，比如打开相册
            return true
        }
    }

    // 在适当的时候调用请求权限的方法
    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun openPictureChooser() {
        if (checkPermissions()) {
            // 如果权限已被授予，则执行相应的操作，比如打开相册
            // 点击图片后，更改图片
            // 打开图片选择器
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            imagePickerLauncher.launch(intent)
        }
    }

    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentWriteArticleBinding,
        viewModel: ArticleFragmentVM?,
        savedInstanceState: Bundle?
    ) {
        // 初始化topPanel
        setTopPanelStyle(viewModel!!, binding)


        // 初始化RV
        initRecyclerView(viewModel, binding)

        // 设置添加新段按钮监听
        binding.addParagraphButton.setOnClickListener {
            val adapter = paragraphRV.adapter as WriteParagraphAdapter
            adapter.addParagraph()
        }

        // 注册图片选择器
        registerImagePickerResult(viewModel)
    }

    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(
        viewModel: ArticleFragmentVM,
        binding: FragmentWriteArticleBinding
    ) {
        val topPanel = binding.topPanel
        val leftImage = topPanel.leftImage
        leftImage.setOnClickListener {
            viewModel.paragraphList.value = arrayListOf()
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }
        topPanel.rightButton.text = "发布"
        topPanel.rightButton.setOnClickListener {
            // 创建确认框
            val builder = AlertDialog.Builder(requireContext())
            builder.setTitle("发布")
            builder.setMessage("你确认发布文章吗")

            // 设置确认按钮和点击事件
            builder.setPositiveButton("确认") { dialog, which ->
                // 发布文章
                // 构造文章对象
                val title = binding.etArticleTitle.text.toString()
                val article = ArticleResponse()
                article.title = title
                viewModel.publishArticle(publicViewModel!!, this, article)
            }

            // 设置取消按钮和点击事件
            builder.setNegativeButton("取消") { dialog, which ->
            }

            // 创建并显示确认框
            val dialog: AlertDialog = builder.create()
            dialog.show()
        }
        val title = topPanel.titleText
        // 群聊名称
        title.text = "文章"
    }

    /**
     * 初始化RV
     */
    private fun initRecyclerView(
        viewModel: ArticleFragmentVM,
        binding: FragmentWriteArticleBinding
    ) {
        // 初始化RV
        paragraphRV = binding.paragraphRV
        // 设置布局排列方式，默认垂直排列
        val linearLayoutManager = LinearLayoutManager(binding.root.context)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        paragraphRV.layoutManager = linearLayoutManager
        // 添加分隔线
        paragraphRV.addItemDecoration(
            DividerItemDecoration(
                binding.root.context,
                LinearLayoutManager.VERTICAL
            )
        )
        // 绑定adapter
        val paragraphList = viewModel.paragraphList.value ?: arrayListOf()
        val writeParagraphAdapter = WriteParagraphAdapter(this, paragraphList)
        writeParagraphAdapter.setOnItemClickListener(object :
            WriteParagraphAdapter.OnItemClickListener {
            @RequiresApi(Build.VERSION_CODES.TIRAMISU)
            override fun onItemClick(imageView: ImageView, position: Int) {
                // 设置点击的图片和位置
                this@WriteArticleFragment.imageView = imageView
                this@WriteArticleFragment.position = position
                uploadImage()
            }
        })
        paragraphRV.adapter = writeParagraphAdapter
    }

    private fun registerImagePickerResult(viewModel: ArticleFragmentVM) {
        imagePickerLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    val selectedImageUri: Uri? = result.data?.data
                    selectedImageUri?.let {
                        val file = getFileFromUri(selectedImageUri)
                        val requestFile = RequestBody.create(MediaType.parse("image/*"), file)
                        val body =
                            MultipartBody.Part.createFormData("file", file!!.name, requestFile)
                        if (body != null && imageView != null) {
                             // Toast.makeText(requireActivity(), "上传中", Toast.LENGTH_SHORT).show()
                            // 将图片上传至服务器，由服务器上传至腾讯云，将返回的地址设为图片地址。
                            viewModel.uploadImageToServer(
                                this, publicViewModel!!, body,
                                imageView!!, position
                            )
                        } else {
                             // Toast.makeText(requireActivity(), "图片未选择", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun uploadImage() {
        openPictureChooser()
    }

    private fun getFileFromUri(uri: Uri): File? {
        val filePath = RealPathUtil.getRealPath(requireActivity(), uri)
        return if (filePath != null) File(filePath) else null
    }

}